package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Course;
import com.example.educationalsystem.entity.Score;
import com.example.educationalsystem.entity.Student;
import com.example.educationalsystem.entity.Vo.ScoreVo;
import com.example.educationalsystem.entity.Vo.ScoreVo;
import com.example.educationalsystem.entity.Vo.SelectCourseVo;
import com.example.educationalsystem.service.IScoreService;
import com.example.educationalsystem.service.IStudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/score",tags = "成绩信息管理")
@RestController
@RequestMapping("/score")
public class ScoreController {
    @Autowired
    private IScoreService iScoreService;
    @ApiOperation(value = "导入课程信息",notes = "导入课程信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, ScoreVo.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            System.out.println(list.size());
            if (list.size() >= 1) {
                for (int i = 0; i < list.size(); i++) {
                    Score score = (Score) list.get(i);
                    System.out.println(score.toString());

                    //使用mybatis-plus添加到数据库
                    Boolean res=iScoreService.save(score);
                    if(res)
                    {
                        responseJson.setStatus(200);
                        responseJson.setMsg("导入成功！");
                    }
                    else {
                        responseJson.setStatus(400);
                        responseJson.setMsg("导入失败！");
                    }
                    System.out.println(res);
                }
            }

        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg(e.toString());
            e.printStackTrace();
        }

        return responseJson;
    }
    @ApiOperation(value = "导出所有成绩信息",notes = "导出所有成绩信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName,@RequestParam(required = false) String studentId) throws IOException {

        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
            if(studentId==null)
            {
                EasyExcel.write(response.getOutputStream(),ScoreVo.class).sheet(tableName).doWrite(iScoreService.getAllScore());
            }
            else{
                EasyExcel.write(response.getOutputStream(),ScoreVo.class).sheet(tableName).doWrite(iScoreService.getScoreByStudentId(studentId));
            }

        }catch(Exception e)
        {
            response.reset();
        }


    }

    @GetMapping("/getScorePage")
    @ApiOperation(value = "获取成绩分页信息",notes = "获取成绩分页信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getScorePage(
                          @RequestParam(value = "size", defaultValue = "10") long size,
                          @RequestParam(value = "current", defaultValue = "1") long current,
                          String studentId,String teacherId
    )
    {
        ResponseJson responseJson=new ResponseJson();
        Page<ScoreVo> page=new Page<>(current,size);
        QueryWrapper<ScoreVo> queryWrapper=new QueryWrapper<>();
        if(studentId==null&&teacherId==null)
        {
            queryWrapper=null;
        }
        if(studentId!=null)
        {
            System.out.println(studentId);
            queryWrapper.eq("a.student_id",studentId);
        }
        if(teacherId!=null)
        {
            System.out.println(studentId);
            queryWrapper.eq("d.teacher_id",teacherId);
        }

        Page<ScoreVo> ScoreVoPage=iScoreService.getScorePage(page,queryWrapper);
        System.out.println(ScoreVoPage.toString());
        if(ScoreVoPage!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(ScoreVoPage);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @GetMapping("/getAllScore")
    @ApiOperation(value = "获取所有成绩信息",notes = "获取所有成绩信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllScore()
    {
        ResponseJson responseJson=new ResponseJson();
        List<ScoreVo> scorelist=iScoreService.getAllScore();
        if(scorelist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(scorelist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无成绩信息！");
        }
        return responseJson;
    }

    @ApiOperation(value = "增加成绩信息信息",notes = "增加一条学生信息记录,必须填写对应的学号和课程编号")
    @PostMapping("/insertScore")
    @ResponseBody
    public ResponseJson insertScore(@RequestBody Score requestScore )
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Score> queryWrapper=new QueryWrapper<>();
        System.out.println(requestScore.getStudentId());
        Score scoreOne=iScoreService.getBaseMapper().selectOne(queryWrapper.eq("student_id",requestScore.getStudentId()).eq("course_id",requestScore.getCourseId()));
        if(scoreOne==null)
        {
            Boolean result=iScoreService.save(requestScore);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestScore);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该成绩信息已存在！");
        }
        return responseJson;
    }

    @ApiOperation(value = "批量删除成绩信息",notes = "根据成绩编号，删除多条成绩信息")
    @DeleteMapping("/deleteScores")
    @ResponseBody
    public  ResponseJson deleteScores( @ApiParam(name = "Ids", value = "成绩IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iScoreService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "删除成绩信息",notes = "根据学号，删除一条成绩信息")
    @DeleteMapping("/deleteScore")
    @ResponseBody
    public  ResponseJson deleteScore( @ApiParam(name = "Id", value = "id", required = true) @RequestParam String Id)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Score> queryWrapper=new QueryWrapper<>();
        int result=iScoreService.getBaseMapper().deleteById(Id);
        System.out.println(result);
        if(result==1)
        {
            responseJson.setData(iScoreService.getBaseMapper().selectOne(queryWrapper.eq("id",Id)));
            responseJson.setMsg("删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("删除失败");
            responseJson.setStatus(400);
        }


        return responseJson;

    }

    @ApiOperation(value = "更新成绩信息",notes = "更新学生成绩信息，必须填写学生ID")
    @PutMapping("/updateScore")
    @ResponseBody
    public ResponseJson updateScore(@RequestBody  Score resquestScore)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Score> queryWrapper=new QueryWrapper<>();
        int result=iScoreService.getBaseMapper().updateById(resquestScore);
        if(result==1)
        {
            responseJson.setMsg("更新成功！");
            responseJson.setStatus(200);
            responseJson.setData(resquestScore);
        }
        else {
            responseJson.setMsg("更新失败！");
            responseJson.setStatus(400);
        }

        return responseJson;
    }
}

